package tsing.javase.redis;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import org.redisson.Redisson;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Redisson配置类
 * @author czw
 */
@ConfigurationProperties(prefix = "spring.redis")
@Configuration
@Data
public class RedissonConfig {
    /**
     * redis单节点地址
     */
    private String host;
    /**
     * redis单节点端口
     */
    private String port;
    /**
     * redis密码
     */
    private String password;
    /**
     * redis集群对象
     */
    private Cluster cluster;

    public static class Cluster {
        private List<String> nodes;
        public List<String> getNodes() {
            return nodes;
        }
        public void setNodes(List<String> nodes) {
            this.nodes = nodes;
        }
    }

    /**
     * 配置redisson
     * Redisson是RedissonClient的实现类
     * @return
     */
    @Bean(destroyMethod = "shutdown")
    public Redisson redisson() {
        //创建Redisson的配置对象
        Config config = new Config();

        //单节点配置
        if(StrUtil.isNotEmpty(host) && StrUtil.isNotEmpty(port)){
            String address = "redis://" + host + ":" + port;
            //使用json序列化方式
            config.setCodec(new JsonJacksonCodec());
            config.useSingleServer().setAddress(address).setPassword(password);
        }
        //集群配置
        else if(cluster != null) {
            List<String> clusterNodes = new ArrayList<>();
            for (int i = 0; i < this.getCluster().getNodes().size(); i++) {
                clusterNodes.add("redis://" + this.getCluster().getNodes().get(i));
            }
            ClusterServersConfig clusterServersConfig = config.useClusterServers()
                    .addNodeAddress(clusterNodes.toArray(new String[clusterNodes.size()]));
            clusterServersConfig.setPassword(getPassword());
        }
        return (Redisson) Redisson.create(config);
    }

}
